const express = require('express')
const route = express.Router();
const advModel = require("../db/model/advModel")
const isLoginMiddle = require("../middleware/isLoginMiddle");
const path = require("path")
const fs = require("fs");

route.delete("/deleteAdv", isLoginMiddle,async (req, res) => {

  const {
    _id
  } = req.query;
//  首先要查询当前ID对应的广告
  console.log('_id',_id)
try {
  const {
    advHref
  } = await advModel.findOne({
    _id
  })
  console.log(advHref)
  const imgName = advHref.split("/")[2];

  //删除这个图片
  // console.log(path.resolve(__dirname, "../upload", imgName));
  fs.unlink(path.resolve(__dirname, "../upload", imgName), () => {
    console.log("删除成功");
  })
}catch (e) {
  console.log('id查询失败请重试'+e.message)
  return res.send({
    code: 10001,
    msg: "删除图片逻辑有错" + e.message,
    data: null
  })
}

//删除数据库的数据
  try {
    const deleteResult = await advModel.deleteOne({
      _id
    })

    res.send({
      code: 10000,
      msg: "删除广告列表成功"+deleteResult,
      data: null
    })
  } catch (e) {
    console.log("删除广告列表失败" + e.message);
    res.send({
      code: 10001,
      msg: "删除广告列表失败" + e.message,
      data: null
    })
  }

})
module.exports = route;